<?php

/**
 * 无限树形数组转树形格式
 * @param $tree 树形结构数组
 * @param int $level 层级
 * @return array
 */
function treeFormat($tree, $level = 0) {
    static $option = array();
    foreach ($tree as $key => $val) {
        $option[$key] = str_repeat('--', $level) . $val['name'];
        if (isset($val['child'])) {
            treeFormat($val['child'], $level+1);
        }
    }
    return $option;
}

/**
 * 数据转无限树形数组
 * @param $data
 * @param $idKey
 * @param $nameKey
 * @param $parentKey
 * @return array
 */
function tree($data, $idKey, $nameKey, $parentKey)
{
    $treeArray = array(); # 树形数组
    $linearStructure = array(); # 线性关系数组
    # 遍历数据集合
    foreach ($data as $val) {
        if (!empty($val[$parentKey])) {
            # 如果没有线性关系的节点，添加新的线性关系，并将节点添加到树形数组中
            if (!isset($linearStructure[$val[$parentKey]])) {
                $linearStructure[$val[$idKey]] = [$val[$parentKey]];
                if (isset($treeArray[$val[$parentKey]])) {
                    $treeArray[$val[$parentKey]]['child'][$val[$idKey]]['name'] = $val[$nameKey];
                } else {
                    $treeArray[$val[$parentKey]]['child'][$val[$idKey]]['name'] = $val[$nameKey];
                }
                continue;
            }
            # 如果线性关系存在则更新线性关系，并将节点按线性关系插入到树形数组的指定位置
            $linear = $linearStructure[$val[$parentKey]];
            $linear[] = $val[$parentKey];
            $linearStructure[$val[$idKey]] = $linear;
            $pointer = &$treeArray;
            foreach ($linear as $node) {
                $pointer = &$pointer[$node]['child'];
            }
            # 移动子节点到当前节点
            if (isset($treeArray[$val[$parentKey]])) {
                $pointer = $treeArray[$val[$parentKey]]['child'];
                unset($treeArray[$val[$parentKey]]);
                continue;
            }
            # 插入子节点
            $pointer[$val[$idKey]]['name'] = $val[$nameKey];
            continue;
        }
        $treeArray[$val[$idKey]]['name'] = $val[$nameKey];
    }
    unset($linearStructure);
    return $treeArray;
}

/**
 * UUID生成
 * @return string
 */
function UUID() {
    #/有重复的可能行，建议谨慎使用
    return md5(uniqid(md5(microtime(true)),true));
}

/**
 * 文件大小单位格式化
 * @param $size
 * @param string $unit
 * @param int $retain
 * @return float
 */
function formatBytes($size, $unit = 'MB', $retain = 2) {
    $units = ['KB', 'MB', 'GB', 'TB'];
    foreach ($units as $val) {
        $size = $size/1024;
        if ($val == $unit) return round($size, $retain);
    }
}

/**
 * 保存图像的base64编码的为文件
 * @param $base64
 * @param $name
 * @param $path
 * @return bool
 */
function base64Image($base64, $name, $path) {
    $base64 = explode(",",$base64);
    $type = $base64[0];
    $type = explode("/",$type);
    $type = explode(";",$type[1]);
    $type = $type[0];
    $base64 = $base64[1];
    $code = base64_decode($base64);
    $fileName = $path . $name . '.' . $type;

    if (!is_dir($path)) {
        if (!@mkdir($path, 0775, true)) return null;
    }
    if(file_put_contents($fileName, $code))  return $name . '.' . $type;
    return null;
}

/**
 * 获取当前服务器IP
 *
 * @return string
 */
function getServerIP()
{
    if(isset($_SERVER)){
        if($_SERVER['SERVER_ADDR']){
            $server_ip=$_SERVER['SERVER_ADDR'];
        }else{
            $server_ip=$_SERVER['LOCAL_ADDR'];
        }
    }else{
        $server_ip = getenv('SERVER_ADDR');
    }
    return $server_ip;
}

/**
 * curl GET请求
 * @param $url
 * @param int $second
 * @return bool|string
 */
function curlGet($url, $second = 30) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $r = curl_exec($ch);
    if (curl_errno($ch) !== 0) {
        return false;
    }
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($status != 200) {
        return false;
    }
    curl_close($ch);
    return $r;
}

/**
 * curl POST请求
 * @param $url
 * @param $param
 * @param int $second
 * @return bool|mixed
 */
function curlPost($url, $param, $second = 30) {
    if (is_array($param)) {
        $param = http_build_query($param);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    if (stripos($url, "https://") !== false) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    }
    $r = curl_exec($ch);
    if (curl_errno($ch) !== 0) {
        return false;
    }
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($status != 200) {
        return false;
    }
    curl_close($ch);
    return $r;
}

/**
 * 当前时间
 * @param null $format
 * @return bool|string
 */
function currentTime($format = null, $time = null) {
    if ($format == null) $format = 'Y-m-d H:i:s';
    if ($time == null) time();
    return date($format, $time);
}

/**
 * URL字符串Base64编码
 * @param $url
 * @return mixed|string
 */
function enBase64URL($url) {
    $data = base64_encode($url);
    $data = str_replace(array('+','/','='),array('-','_',''), $data);
    return $data;
}

/**
 * URL字符串Base64解码
 * @param $url
 * @return mixed|string
 */
function deBase64URL($url) {
    $data = str_replace(array('-','_'),array('+','/'), $url);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

/**
 * 生成带参数的HTTP的URL访问地址
 * @param $path
 * @param $param
 * @return string
 */
function getURL($path, $param) {
    $url = $path;
    if ($param != null && is_array($param)) {
        foreach ($param as $key => $val) {
            $param[$key] = $key . '=' . $val;
        }
        $url .= '?' . implode('&', $param);
    }
    return 'http://' . $_SERVER['HTTP_HOST'] . '/' . $url;
}

/**
 * 比较某个时间是否大于当前时间
 * @param $time 需要比较的时间
 * @param int $interval 时间间隔(秒)
 * @return bool
 */
function compareNowTime($time, $interval = 0)
{
    $time = strtotime($time) + $interval;
    if ($time > time()) return true;
    return false;
}

/**
 * 生成随机数字
 * @param $count 位数
 * @return null|string
 */
function randNumber($count)
{
    $rand = null;
    for($i=0; $i < $count; $i++) {
        $rand .= rand(0, 9);
    }
    return $rand;
}

/**
 * 获取项目根目录文件夹绝对路径
 *
 * @param $name
 * @param $param
 * @return string
 */
function path($name, $param)
{
    $rootPath = app()->basePath($name) . DIRECTORY_SEPARATOR;
    $param = explode('.', $param);
    foreach ($param as $key => $value) {
        $rootPath .= $value . DIRECTORY_SEPARATOR;
    }
    return $rootPath;
}